<?php
namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Dcat\Admin\Admin;
use Illuminate\Support\Facades\Redis;

class SecondDataImport implements ToCollection, WithChunkReading
{
    protected $page = 1;
    protected $legend = [];
    protected $redisKeyPrefix;

    public function __construct() {
        $this->redisKeyPrefix = md5(Admin::user()->id).'_';
        //初始清空reids
        Redis::del($this->redisKeyPrefix.'legend');
        $keys = Redis::keys($this->redisKeyPrefix.'page_*');
        for ($i=1; $i <= count($keys); $i++) { 
            Redis::del($this->redisKeyPrefix.'page_'.$i);
        }
    }

    public function collection(Collection $rows)
    {   
        if ($this->page == 1) {
            $title = $rows->shift()->toArray();
            unset($title[0]);
            $legend = array_values($title);
            $this->legend = $legend;
            Redis::set($this->redisKeyPrefix.'legend', json_encode($legend, JSON_UNESCAPED_UNICODE));
        }

        $xData = [];
        $series = [];
        foreach ($rows->all() as $oneRow) {
            $oneRow = $oneRow->toArray();
            $xData[] = date("H:i:s", strtotime($oneRow[0]));
            unset($oneRow[0]);
            $newOneRow = array_values($oneRow);
            foreach ($newOneRow as $key => $value) {
                $$key[] = $value;
            }
        }
        foreach ($this->legend as $k => $name) {
            $oneSeries['name'] = $name;
            $oneSeries['type'] = 'line';
            $oneSeries['data'] = $$k;
            array_push($series, $oneSeries);
        }
        $onePageData['xData'] = $xData;
        $onePageData['series'] = $series;
        Redis::set($this->redisKeyPrefix.'page_'.$this->page, json_encode($onePageData, JSON_UNESCAPED_UNICODE));
        $this->page++;
    }

    public function chunkSize(): int
    {
        return 3000;
    }
}